<template>
  <div>
    <input v-money v-model="inputBindValue" type="text" />
  </div>
</template>
<script>
export default {
  data() {
    return {
      inputBindValue: null,
    };
  },
  directives: {
    money: (el, binding) => {
      const trimValue = (value, gap = " ") => {
        value = typeof value === "undefined" ? "" : value;
        const reg = new RegExp(gap, "g");
        value = value.toString().replace(reg, "");
        return value;
      };

      function formatCurrentValue(curValue, precision = 2) {
        curValue = trimValue(curValue.replace(/[^\d.]/g, ""));
        const dotPos = curValue.indexOf(".");
        const [moneyCurValue, Decimal] = curValue.split(".");
        const moneyCurDecimal = ~dotPos ? `.${Decimal}` : "";
        let currentValue = "";
        currentValue = moneyCurValue + moneyCurDecimal;
        // 超过需要保留小数位数的内容，进行截取
        if (dotPos !== -1 && Decimal && Decimal.length > precision) {
          currentValue =
            moneyCurValue + moneyCurDecimal.substring(0, precision + 1);
        }
        return currentValue;
      }
      const precision = binding.precision || 2;
      el.oninput = () => {
        el.value = formatCurrentValue(el.value, precision);
      };
      el.oninput();
    },
  },
};
</script>
<style lang="less">
input {
  width: 90%;
}
</style>
